package com.service.sales;

import com.mapper.ProductOrderMapper;
import com.mapper.sales.ProductMapper;
import com.mapper.sales.SalesDetailRMapper;
import com.mapper.sales.SalesOrderDetailMapper;
import com.mapper.sales.SalesOrderMapper;
import com.pojo.Product;
import com.pojo.ShopCartView;
import com.pojo.requestjson.AddSalesProductDetailRequestJson;
import com.pojo.requestjson.ProductList;
import com.pojo.sales.ProductOrder;
import com.pojo.sales.SalesOrder;
import com.pojo.sales.SalesOrderDetail;
import com.pojo.sales.view.SalesDetailR;
import com.service.iter.sales.ISaleOrderService;
import com.service.iter.sales.IZfbService;
import com.util.OrderGenerator;
import com.util.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 销售订单服务业务层
 *
 * @author admin
 * @date 2023/06/20
 */
@Service
@Transactional
public class SaleOrderServiceImpl implements ISaleOrderService {
    /**
     * 销售订单映射器
     */
    @Autowired
    private SalesOrderMapper salesOrderMapper;
    /**
     * 销售订单详情映射器
     */
    @Autowired
    private SalesOrderDetailMapper salesOrderDetailMapper;
    /**
     * 产品订单映射器
     */
    @Autowired
    private ProductOrderMapper productOrderMapper;
    @Autowired
    private SalesDetailRMapper salesDetailRMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private IZfbService zfbService;


    /**
     * 添加销售订单
     *
     * @return {@link HashMap}<{@link String}, {@link Object}>
     */
    @Override
    public Res AddSaleOrder(AddSalesProductDetailRequestJson products) {
        Res res = new Res();
        SalesOrder salesOrder = new SalesOrder();
        LocalDate currentDate = LocalDate.now(); // 获取当前日期
        LocalDate endDate = currentDate.plusDays(7); // 在当前日期上加7天
        final String salesOrderNo = OrderGenerator.generateOrderNumber("sales");
        salesOrder.setEstimatedDeliveryTime(endDate);//预计交货时间
        salesOrder.setSalesOrderNo(salesOrderNo);//生成订单号
        salesOrder.setSalesOrderTime(new Date());//当前时间
        salesOrder.setSalesOrderStatus(1L);//默认创建
        salesOrder.setCustomName(products.getCustomName());
        salesOrder.setCustomPhone(products.getCustomPhone());
        salesOrder.setCustomAddrs(products.getCustomAddress());
        int i = salesOrderMapper.addSalesOrder(salesOrder);
        if (i <= 0) {
            res.setCode(403);
            res.setMsg("销售订单录入失败");
            return res;
        }
        SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
        BigDecimal totalPrice = BigDecimal.valueOf(0);
        for (ProductList product : products.getProductList()) {
            salesOrderDetail.setSalesOrderId(salesOrder.getSalesOrderId());
            salesOrderDetail.setSalesOrderNo(salesOrderNo); // 生成订单号
            salesOrderDetail.setProductId(Long.valueOf(product.getProductId())); // 产品id
            Integer productQuantity = Math.toIntExact(product.getProductQuantity());
            Product productPrice1 = getProductPrice(product.getProductId(), product.getSizeId());
            BigDecimal productPrice = productPrice1.getPrice();
            BigDecimal price = productPrice.multiply(new BigDecimal(productQuantity));
            totalPrice = totalPrice.add(price);
            salesOrderDetail.setSalesDate(new Date());//订单时间
            salesOrderDetail.setProductPrice(productPrice);//产品单价
            salesOrderDetail.setTotalPrice(totalPrice); // 订单总价
            salesOrderDetail.setState(1);
            salesOrderDetail.setProductName(productPrice1.getProductName());
            salesOrderDetail.setProductQuantity(productQuantity);
            salesOrderDetail.setSizeId(product.getSizeId());
            salesOrderDetail.setProductQuantity(productQuantity);
            i = salesOrderDetailMapper.addSalesOrder(salesOrderDetail);
            if (i <= 0) {
                res.setCode(404);
                res.setMsg("销售订单详情录入失败");
                return res;
            }
        }
        salesOrder.setTotalPrice(salesOrderDetail.getTotalPrice());//总金额
        salesOrderMapper.updateSalesOrder(salesOrder);
        res.setCode(200);
        res.setMsg("订单录入成功");
        return res;
    }



    /**
     * 得到销售细节
     *
     * @return {@link List}<{@link SalesDetailR}>
     */
    public List<SalesDetailR> getSalesDetail() {
        return salesDetailRMapper.getSalesDetail();
    }

    /**
     * 获取产品价格
     *
     * @param id     ID
     * @param sizeId 尺寸id。
     * @return {@link Product}
     */
    @Override
    public Product getProductPrice(Integer id, Integer sizeId) {
        Product productPrice = productMapper.getProductPrice(id, sizeId);
        if (Objects.equals(null, productPrice)) {
            return null;
        }
        System.out.println(productPrice);
        return productPrice;
    }

    /**
     * 清空空购物车
     *
     * @param consumerPhone 消费者电话
     * @return {@link Integer}
     */
    @Override
    public Res emptyShopCart(String consumerPhone) {
        Res res = new Res();
        List<ShopCartView> shopCartViews = salesOrderMapper.byConsumerPhoneGetShops(consumerPhone);
        if (shopCartViews.size() < 1) {
            res.setCode(201);
            res.setMsg("购物车内以无商品");
        }
        if (salesOrderMapper.emptyShopCart(consumerPhone) > 0) {
            res.setCode(200);
            res.setMsg("清空购物车成功");
        } else {
            res.setCode(400);
            res.setMsg("清空购物车失败");
        }
        return res;
    }

    @Override
    public Res updateStatus(Long salesOrderId) {
        Res res = new Res();
        try {
            SalesOrder salesOrder = salesOrderMapper.QuerySalesOrder(salesOrderId);
            if (salesOrder == null) {
                res.setCode(404);
                res.setMsg("未找到对应的销售订单");
                return res;
            }
            String salesOrderNo = salesOrder.getSalesOrderNo();
            res = zfbService.queryOrder(salesOrderNo);
            if (res.getCode() != 200) {
                return res;
            }
            Long salesOrderStatus = salesOrder.getSalesOrderStatus();
            if (salesOrderStatus != null && salesOrderStatus == 1L) {
                if (salesOrderMapper.updateStatesById(2L, salesOrderId) < 1 ||
                        salesOrderDetailMapper.updateStatesById(2L, salesOrderId) < 1) {
                    res.setCode(202);
                    res.setMsg("更改订单状态失败，请联系管理员");
                    return res;
                }
            }
            salesOrder.setPaymentTime(new Date());
            salesOrder.setPaymentMethod(1L);
            Res emptyCartRes = emptyShopCart(salesOrder.getCustomPhone());
            if (emptyCartRes.getCode() != 200) {
                res.setCode(emptyCartRes.getCode());
                res.setMsg(emptyCartRes.getMsg());
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
            res.setCode(500);
            res.setMsg("系统异常");
        }
        return res;
    }

    /*

     * 添加产品订单并修改订单状态

     * */
    @Override
    public Res AddProductOrder(Long salesOrderId) {
        Res res = new Res();
        SalesOrder salesOrder = salesOrderMapper.QuerySalesOrder(salesOrderId); //根据订单号查询销售订单表
        String salesOrderNo = salesOrder.getSalesOrderNo();
        List<SalesOrderDetail> salesOrderDetails = salesOrderDetailMapper.QuerySalesOrderDetail(salesOrderId); //根据订单号查询销售订单明细表
        if (salesOrderDetails.isEmpty()) {
            res.setCode(404);
            res.setMsg("空订单");
            System.out.println(res);
            return res;
        }
        final String customAddrs = salesOrder.getCustomAddrs();
        final String customName = salesOrder.getCustomName();
        final String customPhone = salesOrder.getCustomPhone();
        for (SalesOrderDetail salesOrderDetail : salesOrderDetails) {
            final String productOrderNumber = OrderGenerator.generateOrderNumber("product");
            Long productId = salesOrderDetail.getProductId();
            ProductOrder productOrder = new ProductOrder();
            Integer sizeId = salesOrderDetail.getSizeId();
            Product productPrice = productMapper.getProductPrice(Math.toIntExact(productId), sizeId);
            if (productPrice == null) {
                res.setCode(406);
                res.setMsg("产品订单详情录入失败原因没有该此产品大小的对应的价格");
                System.out.println(res);
                return res;
            }
            Product product = productMapper.queryProductById(productId);
            productOrder.setProductOrderCode(productOrderNumber);//生成订单号
            productOrder.setProductId(salesOrderDetail.getProductId());
            productOrder.setProductName(salesOrderDetail.getProductName());
            productOrder.setProductNumber(Long.valueOf(salesOrderDetail.getProductQuantity()));
            productOrder.setCustomName(customName);
            productOrder.setCustomAddress(customAddrs);
            productOrder.setCustomPhone(customPhone);
            productOrder.setProductOrderStatus(1L);
            productOrder.setSizeId(Long.valueOf(salesOrderDetail.getSizeId()));
            productOrder.setCategoryId(product.getProductCategoryId());
            productOrder.setProductMaterial(product.getProductMaterial());
            productOrder.setProductOrderTime(new Date());
            productOrder.setSalesOrderNo(salesOrderNo);
            int i = productOrderMapper.addProductOrder(productOrder);
            if (i <= 0) {
                res.setCode(405);
                res.setMsg("产品订单详情录入失败");
                System.out.println(res);
                return res;
            }
            SalesOrder updatedSalesOrder = salesOrderMapper.QuerySalesOrder(salesOrderId);
            Long salesOrderStatus = updatedSalesOrder.getSalesOrderStatus();
            if (salesOrderStatus == 2L || salesOrderStatus == 10L) {
                System.out.println(salesOrderStatus);
                if (salesOrderStatus == 2L) {
                    salesOrderMapper.updateStatesById(10L, salesOrderId);
                }
                res.setCode(200);
                res.setMsg("产品订单生成成功");
                System.out.println(res);
            } else {
                res.setCode(300);
                res.setMsg("此订单不可再次生成产品订单");
                System.out.println(res);
            }
        }
        return res;
    }

}
